package com.sstir.doctor.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sstir.doctor.common.BusinessResponseEnum;
import com.sstir.doctor.entity.QueListEntity;
import com.sstir.doctor.mapper.QueListMapper;
import com.sstir.doctor.pojo.vo.QuestionVO;
import com.sstir.doctor.result.RespResult;
import com.sstir.doctor.service.IQueListService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hanjunjun
 * @since 2021-01-15
 */
@Service
@Slf4j
public class QueListServiceImpl extends ServiceImpl<QueListMapper, QueListEntity> implements IQueListService {

//    @Value("${business.question-amount}")
//    private int quesAmount;

    @Autowired
    private QueListMapper queListMapper;
    
    @Override
    public RespResult getQuestion(Integer quesCount, String existQueIds) {

        //string转为list
        List<String> exitQuesList = new ArrayList<>();
        if (StringUtils.isNotBlank(existQueIds)){
            String[] idArr = existQueIds.split(",");
            exitQuesList = Arrays.asList(idArr);
        }

        //数据封装
        List<QueListEntity> quesList = queListMapper.getRandomQues(quesCount, exitQuesList);
        if (CollectionUtils.isEmpty(quesList)){
            return RespResult.badRequest(BusinessResponseEnum.DB_NO_SOURCE);
        }
        ObjectMapper objectMapper = new ObjectMapper();
//        objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
        List<QuestionVO> voList = objectMapper.convertValue(quesList, new TypeReference<List<QuestionVO>>() {
        });
        return RespResult.ok(voList);
    }

    @Override
    public RespResult addQuestion(QuestionVO questionVO) {
        QueListEntity entity = new QueListEntity();
        BeanUtils.copyProperties(questionVO, entity);
        if (!save(entity)){
            return RespResult.badRequest(BusinessResponseEnum.BUSINESS_EXCEPTION);
        }
        return RespResult.ok();
    }

}
